package compare;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author : DuJiabao
 * @Date : 2021/1/21 23:17
 * @Project : java_learning
 * @File : null.java
 * @Desc :
 */
public class CompareTest {
    /**
     * Comparable 实现比较
     */
    @Test
    public void test() {
        Commodity[] commodities = new Commodity[100];
        for (int i = 0; i < 100; i++) {
            commodities[i] = new Commodity((int) (Math.random() * 1000));
        }
        Arrays.sort(commodities);
        System.out.println(Arrays.toString(commodities));
    }

    /**
     * Comparator实现比较。通常用于类本身没有Comparable但又需要比较的情况
     */
    @Test
    public void test2() {
        Goods[] goods = new Goods[100];
        for (int i = 0; i < 100; i++) {
            goods[i] = new Goods(Math.random() * 100);
        }

        Arrays.sort(goods, new Comparator<Goods>() {
            @Override
            public int compare(Goods o1, Goods o2) {
                return Double.compare(o1.getPrice(), o2.getPrice());
            }
        });
        System.out.println(Arrays.toString(goods));

    }


}
